package com.cszy.yydqbfq.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager

import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.base.BaseVMFragment
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.PlaylistRepository
import com.cszy.yydqbfq.databinding.FragmentRecommendBinding
import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.ext.clickWithTrigger
import com.cszy.yydqbfq.ext.launch
import com.cszy.yydqbfq.ui.activity.MusicListActivity
import com.cszy.yydqbfq.ui.activity.PlayDetailActivity
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.viewmodel.IndexViewModel
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.lzx.starrysky.SongInfo

class RecommendFragment : BaseVMFragment<IndexViewModel, FragmentRecommendBinding>(),
    IAdViewListener {

    companion object {
        fun newInstance() = RecommendFragment()
    }

    // UI组件
    private var listAdapter: IndexListAdapter? = null
    private var newGromoreFeedAd: NewGroMoreFeedAdManager? = null

    // 数据相关
    private var listIndexData: List<MusicListBean>? = null
    private var currentMusicBean: MusicListBean? = null

    // 状态管理
    private var app_process: String = "0"
    private var type_proces: String? = null
    private var categoryType: String? = null

    // 滚动控制
    private var lastScrollTime = 0L

    override fun initView(savedInstanceState: Bundle?) {
        initRecyclerView()
        setupScrollListener()
    }

    override fun initData() {
        loadMusicData()
        initFeedAd()
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS) ?: "0"
    }

    override fun initListener() {
        setupSectionClickListeners()
        setupListItemClickListeners()
    }

    override fun initObserve() {
        observeMusicData()
    }

    // ==================== 初始化方法 ====================

    private fun initRecyclerView() {
        listAdapter = IndexListAdapter()
        mBinding.recyIndexList.layoutManager = LinearLayoutManager(requireContext())
        mBinding.recyIndexList.adapter = listAdapter
    }

    private fun initFeedAd() {
        newGromoreFeedAd = NewGroMoreFeedAdManager(
            requireActivity(),
            BaseAdConstants.FEEDAD_Id,
            mBinding.feedContainer,
            23
        )
        newGromoreFeedAd?.loadAd()
    }

    private fun setupScrollListener() {
        mBinding.nestScrll.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
            val dy = scrollY - oldScrollY
            if (dy > 0) {
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastScrollTime > 30_000) {
                    loadInterstitialAd()
                    lastScrollTime = currentTime
                }
            }
        }
    }

    // ==================== 数据加载 ====================

    private fun loadMusicData() {
        mViewModel.queryMusic()
    }

    private fun observeMusicData() {
        mViewModel.queryMusicResult.observe(this) { musiclist ->
            Log.e("IndexFragment", "musiclist: $musiclist")
            listIndexData = musiclist as List<MusicListBean>?
            listAdapter?.submitList(musiclist)
            initHorizontalScroll(musiclist)
        }
    }

    // ==================== 点击事件 ====================

    private fun setupSectionClickListeners() {
        mBinding.llRecommend.clickWithTrigger {
            navigateToMusicList("流行")
        }

        mBinding.llLike.clickWithTrigger {
            navigateToMusicList("国风")
        }

        mBinding.llRank.clickWithTrigger {
            navigateToMusicList("金曲榜")
        }
    }

    private fun setupListItemClickListeners() {
        listAdapter?.setOnItemClickListener { adapter, _, position ->
            val songList = mViewModel.convertToSongInfoList(adapter.items)
            val intent = Intent(context, PlayDetailActivity::class.java).apply {
                putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songList))
                putExtra("CURRENT_POSITION", position)
            }
            context?.startActivity(intent)
        }

        listAdapter?.addOnItemChildClickListener(R.id.tv_add_gedanlist) { adapter, _, position ->
            val songItem = adapter.items[position]
            showAddToPlaylistDialog(songItem)
        }
    }

    // ==================== 导航方法 ====================

    private fun navigateToMusicList(category: String) {
        type_proces = "歌曲列表"
        categoryType = category
        AdManager.loadVideo_nocache(requireActivity(), 99, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                launchMusicListActivity(category)
            }
        })
    }

    private fun navigateToPalyDetailActivity() {
        if (currentMusicBean == null) return
        AdManager.loadVideo_nocache(requireActivity(), 99, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                val songInfo = mViewModel.convertToSongInfoList(listOf(currentMusicBean!!))
                val intent = Intent(context, PlayDetailActivity::class.java).apply {
                    putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songInfo))
                    putExtra("CURRENT_POSITION", 0)
                }
                context?.startActivity(intent)
            }
        })
    }

    private fun launchMusicListActivity(category: String) {
        val bundle = Bundle().apply {
            putString("category", category)
        }
        launch(bundle, MusicListActivity::class.java)
    }

    // ==================== UI组件设置 ====================

    private fun initHorizontalScroll(beans: List<MusicListBean>?) {
        val layoutTodayRecommend = mBinding.layoutTodayRecommend
        layoutTodayRecommend.removeAllViews()

        if (beans.isNullOrEmpty()) return

        beans.forEach { bean ->
            val itemView = LayoutInflater.from(requireContext()).inflate(
                R.layout.item_today_recommend,
                layoutTodayRecommend,
                false
            )
            setupHorizontalItemView(itemView, bean)
            layoutTodayRecommend.addView(itemView)
        }
    }

    private fun setupHorizontalItemView(itemView: View, bean: MusicListBean) {
        // 设置封面图片
        itemView.findViewById<ImageView>(R.id.iv_recommend_cover)?.let { imageView ->
            Glide.with(this)
                .load(bean.imageUrl)
                .placeholder(R.mipmap.ic_default)
                .error(R.mipmap.ic_default)
                .apply(RequestOptions().transform(RoundedCorners(30)))
                .into(imageView)
        }

        // 设置标题和艺术家
        val songName = if (app_process == "0") bean.alias ?: "" else bean.name ?: ""
        itemView.findViewById<TextView>(R.id.tv_song_name)?.text = songName
        itemView.findViewById<TextView>(R.id.tv_author)?.text = bean.author ?: ""

        // 设置点击事件
        itemView.setOnClickListener {
            currentMusicBean = bean
            type_proces = "歌曲详情"
            navigateToPalyDetailActivity()
        }
    }

    private fun showAddToPlaylistDialog(songItem: MusicListBean) {
        val song = Song().apply {
            title = songItem.name ?: ""
            artist = songItem.author ?: ""
            cover = songItem.imageUrl ?: ""
            uri = songItem.songUrl
            duration = 0
            songlistbean_id = 0
        }

        val repository = PlaylistRepository()
        val geDanList = repository.getAllPlaylists()
            .filter { it.name != "本地音乐" }

        BottomPopupWithGeDanRecycler(requireActivity(), geDanList, song).show(requireView())
    }

    // ==================== 广告相关 ====================

    private fun loadInterstitialAd() {
        AdManager.loadChapin_nocache(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {}
            }
        )
    }

    override fun onAdClose(adView: IAdView) {
        when (type_proces) {
            "歌曲列表" -> {
                categoryType?.let { launchMusicListActivity(it) }
            }
            "歌曲详情" -> {
                currentMusicBean?.let { bean ->
                    val songInfo = mViewModel.convertToSongInfoList(listOf(bean))
                    val intent = Intent(context, PlayDetailActivity::class.java).apply {
                        putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songInfo))
                        putExtra("CURRENT_POSITION", 0)
                    }
                    context?.startActivity(intent)
                }
            }
        }
    }

    // ==================== 空实现方法 ====================

    override fun onTrigger(adView: IAdView) {}
    override fun onAdShow(adView: IAdView) {}
    override fun onAdClick(adView: IAdView) {}
    override fun onError(msg: String) {}
    override fun onLoadError(adView: IAdView) {}
    override fun onSuccess(adView: IAdView) {}
    override fun onLoad(adView: IAdView) {}
    override fun onSkipped() {}
    override fun onNoAd() {}
    override fun onTimeOut() {}
}


